#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:Vergil
# datetime:2018/9/23 22:32
# software: PyCharm
import logging
from captcha_distinguish import main as cdmain

logger = logging.getLogger('main.p_collect')

headers = {}


def spoc_login(driver, url, captcha_url, username, password):
    start_url = url
    try:
        driver.get(start_url)
    except TimeoutError:
        logger.info('响应超时,停止执行')
        quit()

    cookies = driver.get_cookie('JSESSIONID')['value']
    captcha = cdmain(captcha_url, cookies)

    driver.find_element_by_id('username').send_keys(username)
    driver.find_element_by_id('password').send_keys(password)
    driver.find_element_by_id('authcode').send_keys(captcha)

    driver.find_element_by_xpath("//input[@value='登录']").click()

    if driver.current_url == start_url:
        logger.info('登录成功')
        cookie = driver.get_cookie('ASP.NET_SessionId')['value']

        headers.update({'Content-Type': "application/x-www-form-urlencoded; charset=UTF-8",
                        'Cookie': "ASP.NET_SessionId=" + str(cookie) + "; user_login_account=user_login_account=" + str(username),
                        'X-Requested-With': "XMLHttpRequest",
                        'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
                        })
    else:
        logger.info('登录失败，请重试')
        name = input('学号').strip()
        pwd = input('密码').strip()
        spoc_login(driver, url, captcha_url, name, pwd)

    return headers


def main(driver, url, captcha_url, username, password):
    headers = spoc_login(driver, url, captcha_url, username, password)
    return headers
